// pages/trainingResult/index.js
const app = getApp()
let num = 0;
var result;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    ScoreNum:"",
    integral:"100",
    data:'',
    canvasHide:'',
    qrcode_temp: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    
    result = parseInt(parseInt(getApp().globalData.trainscore) * 0.9 + parseInt(getApp().globalData.time) * 0.1);

    // var result = 80;
     
    that.setData({
      userInfo: getApp().globalData.userInfo,
      ScoreNum: result,
      canvasHide: true,
    })

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          systemInfo: res
        });
      }
    });
    
    if (result >= 50 && 
      parseInt(getApp().globalData.level) == parseInt(getApp().globalData.tollgate))
        {
          that.push(result);
        }else{
      if (parseInt(getApp().globalData.tollgate) == 40){
          that.brush(result);
        }
      }
  },

  bindViewTap:function(){
    wx.redirectTo({
      url: '../index/index'
    })
  },

  push: function (result) {
    let that = this;
    console.log('push!')
    if(num < 3){
  wx.request({
    url: getApp().globalData.url +'/updatetollgate.do',
        method: "GET",
        data: {
          tollgate: parseInt(getApp().globalData.level) + 1,
          openid: getApp().globalData.openid,
          score: result,
          time: 100 - parseInt(getApp().globalData.time)
        },
        header: {
          'content-type': 'json'
        },
        success: function (res) {
          console.log(res);
          if (res.statusCode > 201 && res.data == 0) {
            that.push();
            num++;
          } else if(res.data == 1){
            getApp().globalData.tollgate = parseInt(getApp().globalData.tollgate)+1;
            num = 0;
            console.log('success');
          }
        },
        fail: function (res) {
          that.push();
          num++;
        }
      })
    }
    
  },


  brush: function (result) {
    let that = this;
    console.log('brush!')
    if (num < 3) {
      wx.request({
        url: getApp().globalData.url + '/updateScore.do',
        method: "GET",
        data: {
          tollgate: parseInt(getApp().globalData.level),
          openid: getApp().globalData.openid,
          score: result,
          time: 100 - parseInt(getApp().globalData.time)
        },
        header: {
          'content-type': 'json'
        },
        success: function (res) {
          console.log(res);
          if (res.statusCode > 201 && res.data == 0) {
            that.brush();
            num++;
          } else if (res.data == 1) {
            getApp().globalData.tollgate = parseInt(getApp().globalData.tollgate);
            num = 0;
            console.log('success');
            that.setData({
              data: res.data
            })
          }
        },
        fail: function (res) {
          that.push();
          num++;
        }
      })
    }

  },

  download: function () {
    const that = this;
    wx.downloadFile({
      url: getApp().globalData.url + '/image.png',
      success: function (res) {
        console.log('二维码：' + res.tempFilePath)
        //缓存二维码
        that.setData({
          qrcode_temp: res.tempFilePath
        })
        console.log('开始绘制图片');
        that.drew();
      }
    })
  },

  drew: function () {
    const ctx = wx.createCanvasContext('qrCanvas');
    const that = this;
    let width = that.data.systemInfo.windowWidth * 0.7;
    let height = 300;
    ctx.drawImage('../images/shar.jpg', 0, 0, width+1, height-100)
    ctx.setFillStyle('white')//填充白色
    ctx.fillRect(0, height - 100, width, 100)//坐标x:0,y:height-60 宽高。。。
    ctx.moveTo(width / 2, 20)//画笔移动到垂直居中位置（高度20不重要，我随便写的）
    ctx.setTextAlign('center')//设置文字要垂直居中

    ctx.setFillStyle('#333')//字体颜色
    ctx.setFontSize(15)//字体大小
    ctx.fillText("我在思政理论答题小程序得了"+result+"分", width / 2, height - 75)//字体内容和位置
    ctx.fillText("快来打败我吧！", width / 2 + 20, height - 30)//字体内容和位置
    ctx.drawImage(that.data.qrcode_temp, 10, height - 60, 50, 50)
    ctx.draw()
    that.setData({
      canvasHide: false
    })
  },

  save: function () {
    wx.canvasToTempFilePath({
      canvasId: 'qrCanvas',
      success: function (res) {
        console.log(res)
        wx.hideLoading()
        wx.previewImage({
          urls: [res.tempFilePath]
        })
      }
    })
  },

  hide: function () {
    const that = this;
    that.setData({
      canvasHide: true
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
 
  },
  goon: function (event) {
    let that = this;
    const scorenum = event.currentTarget.dataset.scorenum;
    if (parseInt(getApp().globalData.tollgate) < 40){
      if (scorenum >= 50) {
        wx.showModal({
          title: '提示',
          showCancel: true,//是否显示取消按钮
          cancelText: "分享",//默认是“取消”
          cancelColor: 'skyblue',//取消文字的颜色
          confirmText: "确定",//默认是“确定”
          content: '已解锁下一关',
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../trainingChoice/index',
              });
            } else if (res.cancel) {
              // that.download();
            }
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          showCancel: true,//是否显示取消按钮
          cancelText: "分享",//默认是“取消”
          cancelColor: 'skyblue',//取消文字的颜色
          confirmText: "确定",//默认是“确定”
          content: '得分未超过50分，未解锁下一关',
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../trainingChoice/index',
              });
            } else if (res.cancel) {
              // that.download();
            }
          }
        })
      }
    }else{
      if(that.data.data == 1){
        wx.showModal({
          title: '提示',
          showCancel: true,//是否显示取消按钮
          cancelText: "分享",//默认是“取消”
          cancelColor: 'skyblue',//取消文字的颜色
          confirmText: "确定",//默认是“确定”
          content: '刷分成功，你真棒！',
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../trainingChoice/index',
              });
            } else if (res.cancel) {
              // that.download();
            }
          }
        })
      }else{
        wx.showModal({
          title: '提示',
          showCancel: true,//是否显示取消按钮
          cancelText: "分享",//默认是“取消”
          cancelColor: 'skyblue',//取消文字的颜色
          confirmText: "确定",//默认是“确定”
          content: '刷分失败，再接再厉！',
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../trainingChoice/index',
              });
            } else if (res.cancel) {
              // that.download();
            }
          }
        })
      }
    }
    
  },
  gotoHomepage: function (event) {
    wx.redirectTo({
      url: '../index/index',
    });
  }
})